package tech.aichan.AiQA.controller;

import cn.hutool.http.HttpStatus;
import tech.aichan.AiQA.common.BaseResponse;
import tech.aichan.AiQA.common.ErrorCode;
import tech.aichan.AiQA.constant.RedisConstant;
import tech.aichan.AiQA.exception.BusinessException;
import tech.aichan.AiQA.model.dto.mail.EmailRequest;
import tech.aichan.AiQA.utils.RedisCache;
import tech.aichan.AiQA.utils.SendMailUtil;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

/**
 * @author mengyu
 * @date 2024/03/03 9:52
 */
@RestController
@RequestMapping("/mail")
@Slf4j
public class MailController {
    @Resource
    private SendMailUtil sendMailUtil;
    @Resource
    private RedisCache redisCache;

    @PostMapping("/send")
    public BaseResponse<Integer> sendMail(@Valid @RequestBody EmailRequest emailRequest){
        String email = emailRequest.getEmail();
        // 1.判断是否已经发出过邮件且邮件未过期
        Boolean exist = redisCache.exist(RedisConstant.USER_REG_CODE + email);
        if(exist){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"邮件已发出");
        }
        // 2.发送邮件
        Integer i = sendMailUtil.sendMail(emailRequest.getEmail());
        // 3.放入Redis
        if(i != null){
            redisCache.setCacheObject(RedisConstant.USER_REG_CODE+email,i,5, TimeUnit.MINUTES);
        }
        return BaseResponse.success(HttpStatus.HTTP_OK,null);
    }
}
